<template>
  <view :style="mix_diyStyle">
    <view>
      <view class="fixed_top_bar"></view>
      <view class="main_promote" :style="'background-image:url(' + sharePoster + ')'">
        <!-- #ifdef APP-PLUS -->
        <topHeader :title="$L('我要推广')">
          <view @click="goShare">
            <image :src="imgUrl + 'tshou/share_icon2.png'" mode="aspectFit"></image>
          </view>
        </topHeader>
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <topHeader :back='true'>
          <view @click="goShare">
            <image :src="imgUrl + 'tshou/share_icon2.png'" mode="aspectFit"></image>
          </view>
        </topHeader>
        <!-- #endif -->

        <!-- #ifdef MP -->
        <view class="top_bar">
          <view class="top_header">
            <view class="top_white_space" @click="goShare">
              <image :src="imgUrl + 'tshou/share_icon2.png'" mode="aspectFit"></image>
            </view>
          </view>
        </view>
        <!-- #endif -->

        <!-- 分享弹框 start -->
        <view class="share_model" v-if="share_model" @touchmove.stop.prevent="moveHandle">
          <view class="share_model_list">
            <!-- #ifdef H5 -->
            <view class="share_model_pre" @tap.stop="sldShareBrower(1)" v-if="isWeiXinBrower">
              <image :src="imgUrl + 'goods_detail/wx_share.png'" mode="aspectFit"></image>
              <text>{{ $L('微信好友') }}</text>
            </view>
            <view class="share_model_pre" @tap.stop="sldShareBrower(2)" v-if="isWeiXinBrower">
              <image :src="imgUrl + 'goods_detail/wechat_moments.png'" mode="aspectFit"></image>
              <text>{{ $L('微信朋友圈') }}</text>
            </view>
            <!-- #endif -->
            <!-- #ifdef MP-WEIXIN -->
            <button open-type="share" class="share_model_pre" @click="closeShareModel">
              <image :src="imgUrl + 'goods_detail/wx_share.png'" mode="aspectFit"></image>
              <text>{{ $L('微信好友') }}</text>
            </button>
            <!-- #endif -->
            <!-- #ifdef APP-PLUS -->
            <view class="share_model_pre" @tap.stop="sldShare(0, 'WXSceneSession')">
              <image :src="imgUrl + 'goods_detail/wx_share.png'" mode="aspectFit"></image>
              <text>{{ $L('微信好友') }}</text>
            </view>
            <view class="share_model_pre" @tap.stop="sldShare(0, 'WXSenceTimeline')">
              <image :src="imgUrl + 'goods_detail/wechat_moments.png'" mode="aspectFit"></image>
              <text>{{ $L('微信朋友圈') }}</text>
            </view>
            <!-- #endif -->
            <view class="share_model_pre">
              <image :src="imgUrl + 'goods_detail/poster.png'" mode="aspectFit" @click="getPoster"></image>
              <text>{{ $L('生成海报') }}</text>
            </view>
          </view>
          <view class="share_model_close" @click="closeShareModel">
            <image :src="imgUrl + 'goods_detail/share_close.png'" mode="aspectFit"></image>
          </view>
        </view>
        <!-- 分享弹框 end -->

        <!-- 生成海报  start-->
        <view class="poster" v-if="poster" @touchmove.stop.prevent="moveHandle">
          <!-- 分享海报弹框 start -->
          <view class="share_model" :class="{ poster_share_model: poster }">
           <!-- <image :src="promoteImg" mode="aspectFit" class="poster_image" @longtap.stop="downloadPoster">
            </image> -->
			
			<view class="poster_image" :style="{backgroundImage:`url(${promoteImg})`}" @longtap.stop="downloadPoster">	
			</view>
			
			
            <view class="share_model_list">
              <!-- #ifdef MP-WEIXIN -->
              <view class="share_model_pre" @tap.stop="downloadPoster">
                <image :src="imgUrl + 'goods_detail/poster.png'" mode="aspectFit"></image>
                <text>{{ $L('下载海报') }}</text>
              </view>
              <!-- #endif -->
              <!-- #ifdef APP-PLUS -->
              <view class="share_model_pre" @tap.stop="saveImgAPP">
                <image :src="imgUrl + 'goods_detail/poster.png'" mode="aspectFit"></image>
                <text>{{ $L('保存海报') }}</text>
              </view>
              <view class="share_model_pre" @tap.stop="sldShare(2, 'WXSceneSession')">
                <image :src="imgUrl + 'goods_detail/wx_share.png'" mode="aspectFit"></image>
                <text>{{ $L('微信好友') }}</text>
              </view>
              <view class="share_model_pre" @tap.stop="sldShare(2, 'WXSenceTimeline')">
                <image :src="imgUrl + 'goods_detail/wechat_moments.png'" mode="aspectFit"></image>
                <text>{{ $L('微信朋友圈') }}</text>
              </view>
              <!-- #endif -->
            </view>
            <!-- #ifndef H5 -->
            <view class="share_model_close" @click="closeShareModel">
              <image :src="imgUrl + 'goods_detail/share_close.png'" mode="aspectFit"></image>
            </view>
            <!-- #endif -->
            <!-- #ifdef H5 -->
            <image :src="imgUrl + 'goods_detail/poster_share.png'" mode="aspectFit" class="poster_share_img"
              @longtap.stop="downloadPoster"></image>
            <image :src="imgUrl + 'goods_detail/poster_share_close.png'" mode="aspectFit" class="poster_share_close"
              @click.stop="closePoster"></image>
            <!-- #endif -->
          </view>
          <!-- 分享海报弹框 end -->
        </view>
        <!-- 生成海报  end-->
        <!-- 微信浏览器分享提示  start-->
        <view class="wx_brower_share_mask" v-if="showWeiXinBrowerTip">
          <view class="wx_brower_share_top_wrap">
            <image :src="imgUrl + 'wx_share_tip.png'" mode="widthFix" @tap="closeShareModel" class="wx_brower_share_img">
            </image>
          </view>
        </view>
        <!-- 微信浏览器分享提示  end-->
      </view>
    </view>
  </view>
</template>
<script>
import { WXBrowserShareThen } from '@/utils/common.js'
import { weBtoa } from '@/utils/base.js'
import topHeader from '../component/topheader.vue'
import { mapState } from 'vuex'
export default {
  components: {
    topHeader
  },
  data() {
    return {
      imgUrl: getApp().globalData.imgUrl,
      share_model: false,
      isWeiXinBrower: false,
      showWeiXinBrowerTip: false,
      shareGoods: {},
      poster: false, //生成海报
      sharePoster: getApp().globalData.imgUrl + 'tshou/tsp_bg.png',
      promoteImg: '',
      tmpImage: ''
    }
  },
  onShareAppMessage() {
    return {
      title: `${this.userCenterData.memberNickName
          ? this.userCenterData.memberNickName
          : this.userCenterData.memberName
        }${this.$L('诚挚邀请你一起来做精致分享家')}`,
      desc: this.$L('有钱一起赚，快快加入吧～'),
      path: '/pages/public/register?u=' + weBtoa(this.userCenterData.memberId),
      imageUrl: this.sharePoster
    }
  },
  onShareTimeline() {
    return {
      title: `${this.userCenterData.memberNickName
          ? this.userCenterData.memberNickName
          : this.userCenterData.memberName
        }${this.$L('诚挚邀请你一起来做精致分享家')}`,
      desc: this.$L('有钱一起赚，快快加入吧～'),
      query: 'u=' + weBtoa(this.userCenterData.memberId) + '&from=pyq',
      imageUrl: this.sharePoster
    }
  },
  onLoad() {
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: this.$L('我要推广')
      })
    }, 0);

    if (!this.hasLogin) {
      let urls = this.$Route.path
      const query = this.$Route.query
      uni.setStorageSync('fromurl', {
        url: urls,
        query
      })
      this.$Router.push('/pages/public/login')
    }
    const page = getCurrentPages()
    this.promoteShareImg()
    this.isWeiXinBrower = this.$isWeiXinBrower()
    this.shareGoods = {
      goodsName: `${this.userCenterData.memberNickName
          ? this.userCenterData.memberNickName
          : this.userCenterData.memberName
        }${this.$L('诚挚邀请你一起来做精致分享家')}`,
      goodsBrief: this.$L('有钱一起赚，快快加入吧～'),
      // #ifdef APP-PLUS || H5
      shareLink:
        getApp().globalData.apiUrl +
        'pages/public/register?u=' +
        weBtoa(this.userCenterData.memberId),
      // #endif
      // #ifdef MP-WEIXIN
      shareLink:
        getApp().globalData.apiUrl +
        'pages/public/register?u=' +
        encodeURIComponent(weBtoa(this.userCenterData.memberId)),
      // #endif
      goodsImage: this.sharePoster
    }
    // #ifdef MP-WEIXIN
    if (this.$Route.query.from) {
      this.$Router.replace('/pages/public/register?u=' + this.$Route.query.u)
    }
    // #endif
  },

  onReady() {
    let sharePara = {
      title: this.shareGoods.goodsName,
      desc: this.shareGoods.goodsBrief,
      link: this.shareGoods.shareLink,
      imgUrl: this.shareGoods.goodsImage
    }
    // #ifdef H5
    this.$WXBrowserShareThen(1, sharePara)
    this.$WXBrowserShareThen(2, sharePara)
    // #endif
  },
  computed: {
    ...mapState(['userCenterData', 'hasLogin'])
  },
  methods: {
    goBack() {
      this.$Router.back(1)
    },
    goShare() {
      this.share_model = true
    },
    //浏览器分享
    sldShareBrower(type) {
      this.showWeiXinBrowerTip = true
      this.share_model = false
    },

    //获取海报
    getPoster() {
      this.share_model = false
      this.showWeiXinBrowerTip = false
      this.poster = true
    },

    //分享 type：分享类型 0 图文 2图片，scene 场景 WXSceneSession：分享朋友  WXSenceTimeline：分享朋友圈
    sldShare: function (type, scene) {
      let shareData = {}
      shareData.href = this.shareGoods.shareLink
      shareData.title = this.shareGoods.goodsName
      shareData.summary = this.shareGoods.goodsBrief
      shareData.imageUrl = this.tmpImage
      this.$weiXinAppShare(type, scene, shareData)
      this.closeShareModel() //关闭分享
    },
    //关闭分享弹框
    closeShareModel() {
      this.share_model = false
      this.showWeiXinBrowerTip = false
      this.poster = false
    },

    promoteShareImg() {
      let source = 0
      // #ifdef MP-TOUTIAO
      source = 1
      // #endif
      // #ifdef MP-ALIPAY
      source = 2
      // #endif
      // #ifdef MP-BAIDU
      source = 3
      // #endif
      // #ifdef MP-WEIXIN
      source = 4
      // #endif
      this.$request({
        url: 'v3/spreader/front/spreader/share/spreaderInvitePosters',
        data: {
          source
        },
        responseType: 'arraybuffer',
        dataType: 'arraybuffer'
      }).then((res) => {
        // #ifdef H5
        this.promoteImg =
          'data:image/png;base64,' +
          btoa(
            new Uint8Array(res).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ''
            )
          )
        // #endif
        //#ifdef MP
        this.promoteImg =
          'data:image/png;base64,' +
          weBtoa(
            new Uint8Array(res).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ''
            )
          )
        // #endif
        // #ifdef APP-PLUS
        this.promoteImg =
          'data:image/png;base64,' +
          weBtoa(
            new Uint8Array(res).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ''
            )
          ).replace(/[\r\n]/g, '')
        let that = this
        let base64 = this.promoteImg
        const bitmap = new plus.nativeObj.Bitmap('test')
        bitmap.loadBase64Data(
          base64,
          function () {
            const url = '_doc/' + new Date().getTime() + '.png' // url为时间戳命名方式
            bitmap.save(
              url,
              {
                overwrite: true // 是否覆盖
              },
              (i) => {
                that.tmpImage = i.target
              },
              (e) => {
                bitmap.clear()
              }
            )
          },
          (e) => {
            bitmap.clear()
          }
        )
        // #endif
      })
    },

    //关闭海报
    closePoster() {
      this.poster = false
    },

    downloadPoster() {
      let _this = this
      uni.getSetting({
        success(res_down) {
          if (!res_down.authSetting['scope.writePhotosAlbum']) {
            uni.showModal({
              title: _this.$L('提示'),
              content: _this.$L('您好,需要开启相册权限'),
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  uni.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success() {
                      // 用户已经同意,后续调用时不会弹窗询问
                      _this.saveHb()
                    },
                    fail() {
                      //拒绝授权
                      uni.showToast({
                        title: _this.$L('抱歉，没有授权无法下载海报'),
                        icon: 'none'
                      })
                    }
                  })
                }
              }
            })
          } else {
            _this.saveHb()
          }
        }
      })
      //#ifdef H5
      //阻止浏览器默认行为
      document.oncontextmenu = function (e) {
        e.preventDefault()
      }
      //#endif
    },

    /**
     * 保存图片
     */
    saveHb(img) {
      let code = parseInt(Math.random() * 10000)
      let _this = this
      let { promoteImg } = this
      let that = this
      let base64 = promoteImg.replace(/^data:image\/\w+;base64,/, '') //去掉data:image/png;base64,
      let filePath = wx.env.USER_DATA_PATH + `/image-${code}.png`
      uni.getFileSystemManager().writeFile({
        filePath: filePath, //创建一个临时文件名
        data: base64, //写入的文本或二进制数据
        encoding: 'base64', //写入当前文件的字符编码
        success: (res) => {
          let successPath = res.filePath
          uni.saveImageToPhotosAlbum({
            filePath: filePath,
            success: function (res2) {
              uni.showToast({
                title: that.$L('已保存到本地'),
                icon: 'success',
                duration: 2000
              })
            },
            complete(com) { }
          })
        }
      })
    },

    //APP端保存图片的方法
    saveImgAPP() {
      let _this = this
      let base64 = this.promoteImg
      const bitmap = new plus.nativeObj.Bitmap('test')
      bitmap.loadBase64Data(
        base64,
        function () {
          const url = '_doc/' + new Date().getTime() + '.png' // url为时间戳命名方式
          bitmap.save(
            url,
            {
              overwrite: true // 是否覆盖
            },
            (i) => {
              uni.saveImageToPhotosAlbum({
                filePath: url,
                success: function () {
                  uni.showToast({
                    title: _this.$L('图片保存成功'),
                    icon: 'none'
                  })
                  bitmap.clear()
                }
              })
            },
            (e) => {
              uni.showToast({
                title: this.$L('图片保存失败'),
                icon: 'none'
              })
              bitmap.clear()
            }
          )
        },
        (e) => {
          uni.showToast({
            title: this.$L('图片保存失败'),
            icon: 'none'
          })
          bitmap.clear()
        }
      )
    }
  }
}
</script>

<style lang="scss">
/* #ifdef APP-PLUS */
.fixed_top_bar {
  height: var(--status-bar-height);
  background-color: #fff;
  width: 100%;
}

/* #endif */

.main_promote {
  background-position: center center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  height: 100vh;
  position: absolute;
  width: 750rpx;

  .top_bar {
    width: 750rpx;
    height: 178rpx;
    padding-top: 52rpx;
    padding-right: 20rpx;
    width: 750rpx;
    margin-bottom: 92rpx;

    /* #ifdef APP-PLUS||H5 */
    .top_header {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .top_header_left {
        padding-left: 20rpx;

        image {
          width: 17rpx;
          height: 29rpx;
        }
      }

      .top_header_cen {
        margin: 0 50rpx;
        font-size: 36rpx;
        font-family: PingFang SC;
        color: #ffffff;
      }

      .top_white_space {
        width: 40rpx;
        height: 49rpx;
        padding-right: 20rpx;

        image {
          width: 40rpx;
          height: 40rpx;
        }
      }
    }

    /* #endif */

    /* #ifdef MP*/
    .top_header {
      display: flex;
      align-items: center;
      justify-content: flex-end;

      .top_header_left {
        padding-left: 20rpx;

        image {
          width: 17rpx;
          height: 29rpx;
        }
      }

      .top_white_space {
        width: 40rpx;
        height: 49rpx;
        padding-right: 20rpx;

        image {
          width: 40rpx;
          height: 40rpx;
        }
      }
    }

    /* #endif */
  }
}

.wx_brower_share_mask {
  width: 750rpx;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.45);
  position: absolute;
  z-index: 99999;
  top: 0;
}

.wx_brower_share_top_wrap {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  margin-top: 150rpx;
}

.wx_brower_share_top_wrap .wx_brower_share_img {
  width: 450rpx;
  height: 150rpx;
  margin-right: 80rpx;
}

.share_h5 {
  width: 100% !important;
  height: 100% !important;
}

.share_model {
  width: 750rpx;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  margin: 0 auto;
  background: rgba(0, 0, 0, 0.6);
  z-index: 100;
}

.share_model_list {
  display: flex;
  justify-content: space-around;
  padding: 0 50rpx;
  box-sizing: border-box;
  position: fixed;
  bottom: 150rpx;
  z-index: 110;
  width: 750rpx;

  .share_model_pre {
    display: flex;
    flex-direction: column;
    align-items: center;
    background: transparent;
    border-radius: 0;
    height: auto;
    line-height: auto;

    &::after {
      border-width: 0;
    }

    image {
      width: 105rpx;
      height: 105rpx;
    }

    text {
      font-size: 24rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #ffffff;
      line-height: 36rpx;
      margin-top: 30rpx;
    }
  }
}

.share_model_close {
  width: 46rpx;
  height: 46rpx;
  bottom: 60rpx;
  position: fixed;
  z-index: 110;
  left: 0;
  right: 0;
  margin: 0 auto;

  image {
    width: 46rpx;
    height: 46rpx;
  }
}

button {
  padding: 0;
  margin: 0;
}

.poster {
  width: 750rpx;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  margin: 0 auto;
  background: rgba(0, 0, 0, 0.6);
  z-index: 99999999;

  .poster_image {
    width: 541rpx;
    height: 777rpx;
    border-radius: 20rpx;
    position: absolute;
    left: 105rpx;
    /* #ifdef H5 */
    bottom: 360rpx;
    /* #endif */
    /* #ifndef H5 */
    bottom: 380rpx;
    /* #endif */
    /* #ifdef MP */
    bottom: 330rpx;
    /* #endif */
	
	background-position: center center;
	background-repeat: no-repeat;
	background-size: contain;
  }

  .poster_share_img {
    width: 390rpx;
    height: 90rpx;
    /* left: 179rpx; */
    position: absolute;
    bottom: 177rpx;
    margin: 72rpx 0 22rpx;
  }

  .poster_share_close {
    width: 49rpx;
    height: 49rpx;
    position: absolute;
    /* left: 351rpx; */
    bottom: 105rpx;
  }

  /* #ifdef H5 */
  .poster_share_model {
    width: 750rpx;
    height: 100%;
    position: fixed;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .poster_image {
      width: 541rpx;
      height: 777rpx;
      background-color: #ffffff;
      border-radius: 20rpx;
    }

    .poster_share_img {
      width: 390rpx;
      height: 90rpx;
      margin: 72rpx 0 22rpx;
    }

    .poster_share_close {
      width: 49rpx;
      height: 49rpx;
    }
  }

  /* #endif */
}
</style>
